﻿using IDAL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DAL
{
    /// <summary>
    ///  where是泛型的约束
    ///  where T : class，约束了泛型只能是引用类型
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class BaseDAL<T> : IBaseDAL<T> where T : class
    {
        public BaseDAL(MyContext context)
        {
            Context = context;
        }

        public MyContext Context { get; }

        public async Task<int> AddAsync(T t)
        {
            await Context.Set<T>().AddAsync(t);
            return await Context.SaveChangesAsync();
        }

        public async Task<int> AddRangeAsync(List<T> list)
        {
            await Context.Set<T>().AddRangeAsync(list);
            return await Context.SaveChangesAsync();
        }

        public async Task<int> DeleteAsync(T t)
        {
            Context.Set<T>().Remove(t);
            return await Context.SaveChangesAsync();
        }

        public async Task<int> DeleteRangeAsync(List<T> list)
        {
            Context.Set<T>().RemoveRange(list);
            return await Context.SaveChangesAsync();
        }

        public IQueryable<T> GetAllAsync()
        {
            return Context.Set<T>();
        }

        public async Task<int> UpdateAsync(T t)
        {
            Context.Set<T>().Update(t);
            return await Context.SaveChangesAsync();    
        }

        public async Task<int> UpdateRangeAsync(List<T> list)
        {
            Context.Set<T>().UpdateRange(list);
            return await Context.SaveChangesAsync();
        }
    }
}
